<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/12/19
 * Time: 下午8:30
 */

namespace App\Tables;


use Illuminate\Database\Eloquent\Model;

use DB;
class BaseModel extends Model
{
    /**
     * BaseModel constructor.
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->addGeoCastType();
    }

    /**
     * 地址位置类型数据转换
     * @var array
     */
    protected $geo_fields = ['coordinate'];

    /**
     * Get a new query builder for the model's table.
     *
     * @param bool $excludeDeleted
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function newQuery($excludeDeleted = true)
    {
        $raw = '';

        foreach($this->geo_fields as $column) {
            $raw .= " ST_AsText(`{$column}`) as {$column} ";
        }

        return parent::newQuery($excludeDeleted)->addSelect('*', DB::raw($raw));
    }

    /**
     * 增加geo数据格式转换
     */
    protected function addGeoCastType()
    {
        foreach($this->geo_fields as $column) {
            $this->casts[$column] = 'geo';
        }
    }

    /**
     * 增加地理位置数据格式转换
     * @param string $key
     * @param mixed $value
     * @return array|mixed
     */
    protected function castAttribute($key, $value)
    {
        if (in_array($key, $this->geo_fields)) {
            return $this->fromGeoEntry($value);
        }

        return parent::castAttribute($key, $value);
    }

    /**
     * 转换coordinate格式
     * @param $value
     * @return array
     */
    protected function fromGeoEntry($value)
    {
        preg_match('/^\w+\((.*)\s+(.*)\)$/', $value, $point);

        if (empty($point)) {
            return [];
        }

        $coordinate = [
            'lat' => $point[1],
            'lng' => $point[2]
        ];

        return $coordinate;
    }
}